package edu.zut.main.thread;

public class ThreadMoney {

    public static void main(String[] args) {
        Account account = new Account(100);
        DrawMoneyThread boyDrawMoney = new DrawMoneyThread(account, 60);
        DrawMoneyThread girlDrawMoney = new DrawMoneyThread(account, 30);

        new Thread(boyDrawMoney,"boy").start();
        new Thread(girlDrawMoney,"girl").start();

    }
}

//模拟boy、girl 同时取钱
class DrawMoneyThread implements Runnable{

    private Account account;//操作的账户
    private int drawMoney; //取款额

    public DrawMoneyThread(Account account, int drawMoney) {
        this.account = account;
        this.drawMoney = drawMoney;
    }
    //可以使用同步方法解决同时取款
    @Override
    public void run() {
        //同步代码块   将需要同步的代码放进去 默认同步的是this当前对象
        synchronized (account){
            //取钱的过程
            if (account.getMoney() >= drawMoney){
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                account.setMoney(account.getMoney() - drawMoney);
                System.out.println(Thread.currentThread().getName() + "取完钱之后剩下："+ account.getMoney());
            }else {
                System.out.println(Thread.currentThread().getName() + "余额不足");
                return;
            }
        }

    }
}

//账户
class Account{

    private int money; //余额

    public void setMoney(int money) {
        this.money = money;
    }

    public int getMoney() {
        return money;
    }

    public Account(int money) {
        this.money = money;
    }
}

//有5个苹果3个人吃  多线程模拟如何分苹果
